﻿using System;

namespace FrameWork.Classes
{
    // Summary:
    //     Implements a timer that raises an event at user-defined intervals. This timer
    //     is optimized for use in Windows Forms applications and must be used in a
    //     window.
    public class Timer:IDisposable
    {
        private System.Threading.Timer _timer;
        // Summary:
        //     Initializes a new instance of the System.Windows.Forms.Timer class.
        public Timer()
        {
            _timer = new System.Threading.Timer(TimerCallBack, null, 0, 0);
        }
        public void TimerCallBack(object state)
        {
            if (Enabled&&Interval!=0)
            {
                if (Tick != null)
                {
                    Tick(this, null);
                }
            }
        }
        private bool _enabled = false;
        // Summary:
        //     Gets or sets whether the timer is running.
        //
        // Returns:
        //     true if the timer is currently enabled; otherwise, false. The default is
        //     false.
        public virtual bool Enabled
        {
            get
            {
                return _enabled;
            }
            set
            {
                if(value==_enabled){
                   return;
                }
                _enabled = value;
                if (value)
                {
                    _timer.Change(0, Interval);
                }
                else
                {
                    _timer.Change(0, 0);
                }
            }
        }
        private int _interval = 0;
        //
        // Summary:
        //     Gets or sets the time, in milliseconds, before the System.Windows.Forms.Timer.Tick
        //     event is raised relative to the last occurrence of the System.Windows.Forms.Timer.Tick
        //     event.
        //
        // Returns:
        //     An System.Int32 specifying the number of milliseconds before the System.Windows.Forms.Timer.Tick
        //     event is raised relative to the last occurrence of the System.Windows.Forms.Timer.Tick
        //     event. The value cannot be less than one.
        public int Interval
        {
            get { return _interval; }
            set
            {
                Check.Argument.IsNotNegative(value, "value");
                _timer.Change(0, value);
                _interval = value;
            }
        }

        // Summary:
        //     Occurs when the specified timer interval has elapsed and the timer is enabled.
        public event EventHandler Tick;

        // Summary:
        //     Disposes of the resources, other than memory, used by the timer.
        //
        // Parameters:
        //   disposing:
        //     true to release both managed and unmanaged resources; false to release only
        //     unmanaged resources.
        public void Dispose()
        {
            _timer.Dispose();
        }
    }
}
